package fr.insta.reverse.uml.controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.insta.reverse.uml.routing.Route;

public abstract class DefaultController
{
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	String jspFile;

	public DefaultController(HttpServletRequest _request, HttpServletResponse _response)
	{
		request = _request;
		response = _response;
	}

	public abstract void execute() throws MalformedURLException;

	protected void setMessage(String _message)
	{
		request.setAttribute("message", _message);
	}

	protected String getMessage()
	{
		return request.getAttribute("message").toString();
	}

	/**
	 * Dispatch the request to the template and inflate the content of the jsp file passed as an argument
	 * @param _jspFileName the jsp file name without the extension
	 */
	protected void dispatch(String _jspFileName)
	{
		if (request.getAttribute("dispatched") == null)
		{
			request.setAttribute("dispatched", true);
			request.setAttribute("jspFile", _jspFileName);

			try
			{
				request.getRequestDispatcher("/WEB-INF/template.jsp").include(request, response);
			}
			catch (ServletException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * Dispatch the request to the template and inflate the content of the jsp file passed as an argument
	 * @param _jspFileName the jsp file name without the extension
	 * @param _mapOptions the map options which will be passed as attributes for the jsp file
	 */
	protected void dispatch(String _jspFileName, HashMap<String, Object> _mapOptions)
	{
		Set<Entry<String, Object>> optionValuesJsp = _mapOptions.entrySet();

		for (Entry<String, Object> entry : optionValuesJsp)
			request.setAttribute(entry.getKey(), entry.getValue());

		dispatch(_jspFileName);
	}

	protected void redirect(Route _route)
	{
		try
		{
			response.sendRedirect(_route.getAbsoluteRoute(request));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	protected void redirect(Route _route, String param)
	{
		if (param == null)
			param = "";

		try
		{
			response.sendRedirect(_route.getAbsoluteRoute(request) + param);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
